/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package JFreeChartExtensions.Fitters;

import JFreeChartExtensions.Series.XYExtendedIntervalSeries;
import JFreeChartExtensions.Series.XYRegressionSeries;
import org.apache.commons.math.FunctionEvaluationException;
import org.apache.commons.math.optimization.OptimizationException;
import org.apache.commons.math.optimization.fitting.GaussianFitter;
import org.apache.commons.math.optimization.fitting.GaussianFunction;
import org.apache.commons.math.optimization.general.LevenbergMarquardtOptimizer;

/**
 *
 * @author Nobody
 */
public class GaussianReggresion implements IReggression {

    public int PRECISE = 100;
    private String lastFunctionFormula;

    @Override
    public XYRegressionSeries regress(XYExtendedIntervalSeries series) throws OptimizationException {

        XYRegressionSeries regr = null;
        try {

            LevenbergMarquardtOptimizer optimizer = new LevenbergMarquardtOptimizer();
            GaussianFitter fitter = new GaussianFitter(optimizer);
            for (int i = 0; i < series.getItemCount(); ++i) {
                fitter.addObservedPoint(1, (Double) series.getX(i), (Double) series.getYValue(i));
            }
            GaussianFunction gaussianFunction = fitter.fit();
            lastFunctionFormula = gaussianFunction.toString();

            regr = new XYRegressionSeries(lastFunctionFormula);
            for (double x = series.getMinX(); x < series.getMaxX(); x += (series.getMaxX() - series.getMinX()) / PRECISE) {
                regr.add(x, 0, 0, gaussianFunction.value(x), 0, 0);
            }
        } catch (FunctionEvaluationException ex) {
            throw new OptimizationException(ex);
        }
        return regr;
    }

    @Override
    public String toString() {
        return "GaussianReggresion";
    }
}
